import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../../common/api/x_message_assemble_communicate.dart';
import '../../../../common/models/im/im_message.dart';
import '../../../../common/utils/loading.dart';
import '../../../../common/utils/o2_api_manager.dart';
import '../../../../common/values/o2.dart';
import '../../../../common/widgets/o2_stateless_widget.dart';
import '../chat_message_tool.dart';
import 'index.dart';

class ImMessageCollectionController extends GetxController {
  ImMessageCollectionController();

  final state = ImMessageCollectionState();
  final messageTool = ImChatMessageTool();

  bool _isLoading = false; // 是否正在加载
  final refreshController = RefreshController();
  Map<String, String> headers = {};

  int page = 1;

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    messageTool.init();
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    headers[O2ApiManager.instance.tokenName] =
        O2ApiManager.instance.o2User?.token ?? '';
    refreshData();
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    messageTool.dispose();
    super.onClose();
  }

  /// 点击消息列表项
  void clickMsgItem(IMMessage msg) {
    messageTool.clickMsgItem(msg);
  }

  /// 点击切换模式
  void clickChangeMode() {
    state.selectMode = !state.selectMode;
    state.selectedList.clear();
  }

  /// 点击删除消息
  void clickDeleteMsgs() {
    final context = Get.context;
    if (context == null) return;
    final msgList = state.selectedList.toList();
    if (msgList.isEmpty) {
      Loading.toast('im_chat_error_message_select_empty'.tr);
      return;
    }
    O2UI.showConfirm(context, 'im_chat_message_collection_delete_confirm'.tr,
        okPressed: () => deleteCollections(msgList));
  }

  void clickChooseMsg(IMMessageCollection msg) {
    if (state.selectedList.contains(msg)) {
      state.selectedList.removeWhere((e) => e.id == msg.id);
    } else {
      state.selectedList.add(msg);
    }
  }

  /// 选中消息
  bool isMessageSelected(IMMessageCollection msg) {
    return state.selectedList.contains(msg);
  }

  Future<void> deleteCollections(List<IMMessageCollection> msgList) async {
    final msgIdList = msgList.map((e) => e.id!).toList();
    final result =
        await MessageCommunicationService.to.collectionMessageDelete(msgIdList);
    if (result != null) {
      state.selectMode = false;
      state.selectedList.clear();
      for (var msg in msgList) {
        state.msgList.removeWhere((e) => e.id == msg.id);
      }
      Loading.toast('im_chat_message_collection_delete_success'.tr);
    }
  }

  /// 刷新主题帖子数据
  Future<void> refreshData() async {
    if (_isLoading) return;
    _isLoading = true;
    page = 1;
    await loadCollectionMessageList();
    refreshController.refreshCompleted();
  }

  /// 获取更多主题帖子数据
  Future<void> loadMore() async {
    if (_isLoading) return;
    if (!state.hasMoreData) {
      refreshController.loadComplete();
      return;
    }
    _isLoading = true;
    page++;
    await loadCollectionMessageList();
    refreshController.loadComplete();
  }

  Future<void> loadCollectionMessageList() async {
    _isLoading = true;
    if (page == 1) {
      state.msgList.clear();
    }

    final messageList =
        await MessageCommunicationService.to.collectionMessageListByPage(page);
    if (messageList != null && messageList.isNotEmpty) {
      state.msgList.addAll(messageList);
      state.hasMoreData = !(messageList.length < O2.o2DefaultPageSize);
    } else {
      state.hasMoreData = false;
    }
    _isLoading = false;
  }
}
